package com.king.login.utils;

import com.king.login.entity.MemberMenu;
import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MenuUtils
{
  public static <T> void changeBeantoMap(Map<String, Object> map, T t)
  {
    if (t != null)
    {
      BeanMap beanMap = BeanMap.create(t);
      for (Object key : beanMap.keySet())
      {
        map.put(key + "", beanMap.get(key));
      }
    }

  }


  public static <T extends MemberMenu> Map<String, Object> filterMenu(List<T> list)
  {
    Map<String, Object> menuList = new LinkedHashMap<>();

    //获取一级菜单
    List<T> menu = list.stream().filter(item -> item.getMenuLevel() == 1).collect(Collectors.toList());
    List<T> subMenuList = new ArrayList<>();

    //组装二级菜单
    menu.forEach(item ->
    {
      changeBeantoMap(menuList, item);

      list.forEach(subMenu ->
      {
        if (!subMenu.getParentId().equals(0) && item.getId().equals(subMenu.getParentId()))
        {
          subMenuList.add(subMenu);
        }
      });
      menuList.put("children", subMenuList);
    });

    return menuList;
  }

}
